package uk.ac.glasgow.demosocs.users;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/** A simple file based implementation of a store for users. */
public class UserStoreImpl implements UserStore {

	private Map<String,User> users;
	private File storeFile;
	
	/**
	 * Constructs a new store in the specified file location.
	 * @param fileName
	 */
	public UserStoreImpl(String fileName){
		System.out.println("User store created with filename:" + fileName);
		storeFile = new File(fileName);
		//System.out.println("Trying to crete user store from file:" + fileName);
		int numberOfUsers = 0;
		if (storeFile.exists()){
			this.users = new HashMap<String,User>();
			//System.out.println("File exists.");
			Scanner in = null;
			try {
				in = new Scanner(storeFile);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			while (in.hasNext()){
				String guid = in.next();
				String surname = in.next();
				String forename = in.next();
				String password = in.next();
				String userType = in.next();
				//System.out.println(guid + " " + surname + " " + forename + " " + password+".");
				User user = new User(surname, forename, guid, password);
				
				if (userType.equals("M")){
					user.makeManager();
				}
				else if (userType.equals("V")){
					user.makeVoter();
				}
				users.put(guid, user);
				numberOfUsers++;
			}
			System.out.println("User store has been constructed with " + numberOfUsers + " Users.");
		}
		else {
			System.out.println("File does not exist");
			this.users = new HashMap<String,User>();
		}
		
		
		
	}
	
	@Override
	public void addUser(String surname, String forename, String GUID, String password) {
		User user = new User(surname,forename,GUID,password);
		users.put(GUID,user);
		
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(storeFile));
			oos.writeUTF(GUID);
			oos.writeObject(user);
			oos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
		

	@Override
	public User getUser(String GUID, String password) {
		User user = users.get(GUID);
		return ((user != null && user.authenticate(password))? user : null);
	}
	
	public Map<String,User> getUsers(){
		return this.users;
	}

}
